<?php
/*******************************************
  Captcha (because we cannot use reCaptcha)
*******************************************/

// Avoid direct access
if(substr_count($_SERVER['PHP_SELF'], 'captcha.php') > 0) {
	header("HTTP/1.0 404 Not Found");
	exit;
}


class Captcha {

	/**
	 * Creazione codice di sicurezza
	 *
	 * @param unknown_type $numchar
	 * @param unknown_type $dir
	 * @param unknown_type $background
	 * @param unknown_type $color
	 * @return unknown
	 */
	public static function genCaptcha($code, $image_name)
	{		
		$dir = CAPTCHA_DIR;
		$image_name = $image_name.".png";
		
		// delete old codes
		$handle = opendir($dir."/");
		while ($file = readdir($handle)) 
		{ 
			if((file_exists($dir."/".$file)) && (is_file($dir."/".$file)))
			{
				unlink($dir."/".$file);
			}
		}
		$handle = closedir($handle);	
		
		// create image
		$im = ImageCreateTrueColor(80, 30);

		// fill the background
		$r = hexdec(substr(CAPTCHA_BGCOLOR, 0,2));
		$g = hexdec(substr(CAPTCHA_BGCOLOR, 2,2));
		$b = hexdec(substr(CAPTCHA_BGCOLOR, 4,2)); 
		$bgcolor = ImageColorAllocate($im, $r, $g, $b);
		ImageFillToBorder($im, 0, 0, $bgcolor, $bgcolor);		
	
		// create text
		$r = hexdec(substr(CAPTCHA_COLOR, 0,2));
		$g = hexdec(substr(CAPTCHA_COLOR, 2,2));
		$b = hexdec(substr(CAPTCHA_COLOR, 4,2)); 		
		$color = ImageColorAllocate($im, $r, $g, $b);
		
		imagettftext($im,23,3,8,26,$color,CAPTCHA_FONT,$code);
		imagepng($im, CAPTCHA_DIR."/".$image_name);
		imagedestroy($im);
									
	}
	
	
	/**
	 * Crypt
	 *
	 * @param unknown_type $data
	 * @param unknown_type $key
	 * @return unknown
	 */
	public static function Crypt($data,$key)
	{		
		if(strlen($key)<32) $key = md5($key);
		$ld  = strlen($data);
		$lk  = strlen($key);
		for($i=0, $crdata=""; $i<$ld; $i++)
		{
			$crdata .= sprintf("%02X",(ord($data[$i]))^(ord($key[$i%$lk])));
		}
		
		unset($ld,$lk);	
		
		return $crdata;
		
	}	

	
	/**
	 * Decrypt
	 *
	 * @param unknown_type $cdata
	 * @param unknown_type $key
	 * @return unknown
	 */
	public static function deCrypt($cdata,$key)
	{		
		if(strlen($key)<32) $key = md5($key);
		$ld  = strlen($cdata);
		$lk  = strlen($key);
		for($i=0, $data=""; $i<$ld; $i+=2)
		{
			$data .= chr((hexdec(substr($cdata, $i, 2)))^(ord($key[($i>>1)%$lk])));
		}

		unset($ld,$lk);	

		return $data;
	}	

	
	/**
	 * Crea codice casuale
	 *
	 * @param unknown_type $numchar
	 * @return unknown
	 */
	public static function createCode($numchar)
	{
		$code = "";
		
		for($i=0;$i<$numchar;$i++)
		{		
			do
			{
				$N = ceil(rand(48,122));
			}while(!((($N >= 48) && ($N <= 57)) || (($N >= 65) && ($N <= 90)) || (($N >= 97) && ($N <= 122))));							
			
			$code = $code.chr($N);	
		}	
		
		return $code;

	}

}

?>